package com.gxa.customer.security.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.commons.R;
import com.gxa.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyLogoutHandler implements LogoutHandler {

    //@Autowired,不用自动注入，退出的时候才注入依赖进来，所以用构造方法更合适
    private RedisTemplate redisTemplate;

    public MyLogoutHandler(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        //1.在header头中删除掉token
        String token = httpServletRequest.getHeader("Authorization");
        if(token!=null&&!"".equals(token)){
            //从token获取用户名
            String username = JwtUtils.parseJWT(token).getSubject();
            //1.移除Authorization
            redisTemplate.delete(username);
        }
        R r = new R();
        r.setCode(200);
        r.setMsg("注销成功");
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try {
            httpServletResponse.getWriter().write(JSONObject.toJSONString(r));
            httpServletResponse.getWriter().flush();
            httpServletResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
